# -*- coding: utf-8 -*-

# -------------------------------
# Author    : linlingwei
# Email     : 951035650@qq.com
# File Name : lRigMenuCmd.py
# Date      : 2018/8/25
# IDE       : PyCharm
# Version   : 1.0.1
# -------------------------------

import os
import sys
import getpass

from configs.constants.global_constant import *

import maya.cmds as mc
import maya.mel as mel
import pymel.core as pm

import scripts.lHotkey as lHotkey
import scripts.commonCmds as con
import scripts.deformerCmds as dc
import editors.editor as editor
import editors.name_editor as name_editor
import editors.check_editor as check_editor
import editors.facial_editor as facial_editor
import editors.control_editor as control_editor
import editors.blendShape_editor as blendShape_editor
import editors.driver_editor as driver_editor
# import editors.bodyRig_editor as bodyRig_editor
import editors.setDriverKeyframe_editor as setDriverKeyframe_editor
import editors.rig_editor as rig_editor
import editors.bodyRig_editor as bodyRig_editor

__author__ = "lin lingwei"
__version = "1.3.2"
menuName = "lRigMenu"
gMainWindow = mel.eval('$gMainWindow=$gMainWindow')
# userMayaScriptPath = "C:/Users/{}/Documents/maya/scripts".format(getpass.getuser())

def setup():
    
    remove()
    
    editorShowWindow = "reload(lRigMenuCmd.{module});lRigMenuCmd.{module}.showEditor()"
    mc.menu(menuName, l="@ Rig ...", p=gMainWindow, tearOff=True, aob=True)
    
    mc.menuItem("addSelectEmptyGroup",l="Add Select Empty Group",sourceType="python",
                c='lRigMenuCmd.addSelectEmptyGroup()')
    mc.menuItem(optionBox=True,c="lRigMenuCmd.addSelectEmptyGroupOption()")
    
    # ----
    commonItem()
    skinClusterItem()
    # ----
    
    mc.menuItem( divider=True, dividerLabel='Editor ...')
    mc.menuItem("nameEditor",l="Name Editor",c=editorShowWindow.format(module="name_editor"))
    mc.menuItem("checkEditor",l="Check Editor",c=editorShowWindow.format(module="check_editor"))
    mc.menuItem("controlEditor",l="Control Editor",c=editorShowWindow.format(module="control_editor"))
    mc.menuItem("driverEditor",l="Driver Editor",c=editorShowWindow.format(module="driver_editor"))
    mc.menuItem("blendShapeEditor",l="BlendShape Editor",c=editorShowWindow.format(module="blendShape_editor"))
    mc.menuItem("setDriverKeyframeEditor",l="SetDriverKeyframe Editor",
                c=editorShowWindow.format(module="setDriverKeyframe_editor"))

    # mc.menuItem("bodyRigEditor",l="Body Editor",c="lRigMenuCmd.bodyRig()")
    mc.menuItem("rigEditor",l="Rig Editor",c=editorShowWindow.format(module="rig_editor"))
    mc.menuItem("bodyEditor",l="Body Editor",c=editorShowWindow.format(module="bodyRig_editor"))
    mc.menuItem("facialEditor",l="Facial Editor",c=editorShowWindow.format(module="facial_editor"))

    mc.menuItem( divider=True, dividerLabel='Setting ...')
    mc.menuItem("hotkey", l="Hotkey Setting ...", c="lRigMenuCmd.reloadHotkey()")
    mc.menuItem(optionBox=True, c="lRigMenuCmd.lHotkey.hotkeyCmd('help')")
    
    mc.menuItem(divider=True, dividerLabel="Site-Packages")
    mc.menuItem("site-packages",l="Site-Packages ...",subMenu=True,tearOff=True)
    mc.menuItem("ngSkinTools",l="NgSkinTools",c="lRigMenuCmd.ngSkinTools()",i=os.path.join(gIconPath,"ngSkinTools.ico"))
    mc.setParent('..', menu=True)
    
    mc.menuItem("about",divider=True, dividerLabel='About')
    mc.menuItem("lAbout",l="About Rig Menu",i=os.path.join(gIconPath,"mainLogo.svg"),c="lRigMenuCmd.about()")

    refreshButton()
def remove():
    if mc.menu(menuName, q=True, ex=True):
        mc.deleteUI(menuName, m=True)
    
    return
def restart():
    setup()
    pm.displayInfo("Result: Rig Menu is restart.")
    return
def refreshButton():
    gModelingToolkitButton = mel.eval("$tmp = $gModelingToolkitButton;")
    pform = mc.iconTextCheckBox(gModelingToolkitButton, q=True, p=True)
    
    image = os.path.join(gIconPath,"mainLogo.svg")
    refreshBtn = mc.iconTextButton("{}RefreshButton".format(__author__), p=pform, st="iconOnly", h=22, w=22,
                                   i=image,
                                   c="reload(lRigMenuCmd);lRigMenuCmd.restart()")
    mc.formLayout(pform, e=True,
                  attachForm=[(refreshBtn, "top", 1), ],
                  attachControl=[gModelingToolkitButton, "left", 1, refreshBtn],
                  attachNone=[(refreshBtn, "bottom"),
                              (refreshBtn, "right")]
    
                  )
    return
def removeRefreshButton():
    mc.deleteUI("{}RefreshButton".format(__author__))
    return
def reloadHotkey():
    reload(lHotkey)
    lHotkey.setup()
    pm.displayInfo("Result: lHotkey is restart.")
    return
def about():
    
    _win = "aboutLRigForMaya"
    editor.Editor().isExist(_win)
    win = mc.window(_win,t="About LRig For Maya")
    mc.window(win,e=True,wh=[400,400],s=False)
    mc.columnLayout(adj=True)
    # print os.path.join(gIconPath,"main_about.png")
    mc.picture(i=os.path.join(gIconPath,"main_about.png"))
    # mc.text("-")
    mc.separator()
    mc.text("Author : {}".format(__author__))
    mc.text("Version : {}".format(__version))
    mc.separator()
    # mc.scrollLayout()
    with open(os.path.join(gPath,"update.log"),"r") as fu:
        tx = fu.read()
    mc.scrollField(w=300,ed=False,tx=tx,ww=True)
    editor.Editor().copyright()
    mc.setParent("..")
    mc.showWindow()
    return
def bodyRig():

    import sys
    bpath = os.path.join(gSitePackagesPath, "python")
    if bpath not in sys.path:
        sys.path.append(bpath)
        
    cmd1 = "from window import bodyRig_editor;reload(bodyRig_editor)"
    # cmd1 = "import window.bodyRig_editor as bodyRig_editor;reload(bodyRig_editor)"
    cmd2 = "bodyRig_editor.showEditor()"
    mel.eval('python("{}")'.format(cmd1))
    mel.eval('python("{}")'.format(cmd2))
    return
def ngSkinTools():
    mayaVer = mc.about(v=True)
    
    ngSkinToolsLocalPath = os.path.join(gSitePackagesPath, "ngskintools\Contents")
    ngSkinToolsLocalScriptPath = os.path.join(ngSkinToolsLocalPath, "scripts")
    ngSkinToolsLocalPluginPath = os.path.join(ngSkinToolsLocalPath, "plug-ins", mayaVer)
    
    # if not os.path.exists(ngSkinToolsLocalPath):
    #     import zipfile
    #     zipPath = os.path.split(__file__)[0].split("toolkit")[0] + "crvData"
    #     ngZip = "ngskintools-1.7.6-windows.zip"
    #     print os.path.join(zipPath, ngZip)
    #
    #     with zipfile.ZipFile(os.path.join(zipPath, ngZip), "r") as zf:
    #         for line in zf.namelist():
    #             zf.extract(line, "{}/".format(userMayaScriptPath))
    
    listPlugins = mc.pluginInfo(query=True, listPlugins=True)
    ngSkinToolsPluginsName = "ngSkinTools"
    if ngSkinToolsPluginsName not in listPlugins:
        if ngSkinToolsLocalPluginPath not in os.environ["MAYA_PLUG_IN_PATH"]:
            os.environ["MAYA_PLUG_IN_PATH"] += ";{}".format(ngSkinToolsLocalPluginPath)

        mc.loadPlugin(ngSkinToolsPluginsName)

    if ngSkinToolsLocalScriptPath not in sys.path:
        sys.path.append(ngSkinToolsLocalScriptPath)
    
    SetupCmd1 = "from ngSkinTools.ui.mainwindow import MainWindow"
    SetupCmd2 = "MainWindow.open()"
    
    mel.eval('python("{}")'.format(SetupCmd1))
    mel.eval('python("{}")'.format(SetupCmd2))
    return


def commonItem():
    mc.menuItem('common', l="Common ...", subMenu=True, tearOff=True)
    mc.menuItem("lCommon", divider=True, dividerLabel='Common Toolkit')
    mc.menuItem("resetJointOrient", l="Reset Joint Orient", c="lRigMenuCmd.resetJointOrient()")
    mc.menuItem(divider=True)
    mc.menuItem("showJoint", l="Show Joint", c="lRigMenuCmd.hideAllJoint(False)")
    mc.menuItem("hideJoint", l="Hide Joint", c="lRigMenuCmd.hideAllJoint()")
    mc.menuItem(divider=True)
    mc.menuItem("showLocator", l="Show Locator", c="lRigMenuCmd.hideAllLocator(False)")
    mc.menuItem("hideLocator", l="Hide Locator", c="lRigMenuCmd.hideAllLocator()")
    
    mc.setParent('..', menu=True)
    
    return


# -----------

def addSelectEmptyGroup(emptyStrs=['Zero']):
    sel = mc.ls(sl=True)
    if not sel:
        return
    for sl in sel:
        con.emptyGroup(sl, emptyStrs)
    return


def addSelectEmptyGroupOption():
    ann = "addSelectEmptyGroupOption"
    if mc.window(ann, q=True, ex=True):
        mc.deleteUI(ann, wnd=True)
    win = mc.window(ann, t="Add Select Empty Group Option", wh=[265L, 80L], s=True)
    mc.columnLayout(ann + "_column", adj=True)
    mc.textField(ann + "_textField", tx="Zero;")
    mc.separator(style='in', h=5)
    mc.button(ann + "_button", l="Empty Group", c=lambda *args: addSelectEmptyGroupOptionCmd())
    mc.separator(style='out', h=5)
    editor.Editor().copyright()
    
    mc.setParent("..")
    mc.showWindow(win)
    return


def addSelectEmptyGroupOptionCmd():
    ann = "addSelectEmptyGroupOption"
    tx = mc.textField(ann + "_textField", q=True, tx=True).split(";")
    tx_n = list()
    for t in tx:
        if t != '':
            tx_n.append(t)
    addSelectEmptyGroup(tx_n)
    return


def hideAllJoint(hide=True):
    joints = mc.ls(type="joint")
    for jot in joints:
        if hide:
            mc.setAttr(jot + ".drawStyle", 2)
        else:
            mc.setAttr(jot + ".drawStyle", 0)
    
    return


def hideAllLocator(hide=True):
    locs = mc.ls(type="locator")
    for loc in locs:
        if hide:
            mc.setAttr(loc + ".v", 0)
        else:
            mc.setAttr(loc + ".v", 1)
    
    return


def resetJointOrient():
    for sl in mc.ls(sl=True):
        if mc.nodeType(sl) == "joint":
            mc.setAttr("{}.jointOrient".format(sl), 0, 0, 0)
    return

def skinClusterItem():
    mc.menuItem('skinCluster', l="SkinCluster ...", subMenu=True, tearOff=True)
    
    mc.menuItem( divider=True, dividerLabel='SkinCluster')
    # mc.menuItem("selectSkinClusterNode",l="select SkinCluster Node")
    mc.menuItem("selectSkinClusterJoint", l="Select SkinCluster Joint", c="lRigMenuCmd.selectSkinCluster()")
    mc.menuItem("resetSkinClusterBindPose", l="Reset SkinCluster BindPose",
                c="lRigMenuCmd.resetSelectSkinClusterBindPose()")

    mc.menuItem( divider=True)
    mc.menuItem("lockSelectInfJoint", l="Lock Select InfJoint", c="lRigMenuCmd.lockSelectInfJoint()")
    mc.menuItem("unlockSelectInfJoint", l="Unlock Select InfJoint", c="lRigMenuCmd.lockSelectInfJoint(False)")
    
    mc.menuItem("lSkinCluster2", divider=True)
    mc.menuItem("lockAllInfJoint", l="Lock All InfJoint", c="lRigMenuCmd.lockAllJointWeight()")
    mc.menuItem("unlockAllInfJoint", l="Unlock All InfJoint", c="lRigMenuCmd.lockAllJointWeight(False)")
    
    mc.menuItem(divider=True)
    mc.menuItem("pruneAllSmallWeight", l="Prune All Small Weight", c="lRigMenuCmd.pruneSmallWeight(1)")
    mc.menuItem("pruneSelectSmallWeight", l="Prune Select Small Weight", c="lRigMenuCmd.pruneSmallWeight(0)")
    
    mc.menuItem(divider=True)
    mc.menuItem("removeAllUnusedInf", l="Remove All Unused Inf",
                c="lRigMenuCmd.removeUnusedSkinClusterInf(1)")
    mc.menuItem("removeSelectUnusedInf", l="Remove Select Unused Inf",
                c="lRigMenuCmd.removeUnusedSkinClusterInf(0)")
    
    mc.menuItem(divider=True)
    mc.menuItem("exportSkinClusterWeight", l="Export SkinCluster Weight",
                c="lRigMenuCmd.exportSelectSkinClusterWeight()")
    mc.menuItem("importSkinClusterWeight", l="Import SkinCluster Weight",
                c="lRigMenuCmd.importSelectSkinClusterWeight()")
    
    mc.setParent('..', menu=True)
    return

# -------------------

def selectSkinCluster():
    sel = mc.ls(sl=True)
    if sel:
        skinNode = dc.findRelatedDeformer(sel[0])
        if skinNode:
            infJoint = mc.skinCluster(skinNode, q=True, inf=True)
            if infJoint:
                mc.select(infJoint)
    
    return


def lockAllJoint(lock=True):
    for jot in mc.ls(type="joint"):
        try:
            mc.setAttr(jot + ".liw", lock)
        except:
            raise
    return


def lockSelectInfJoint(lock=True):
    sel = mc.ls(sl=True)
    for sl in sel:
        dc.lockInf(sl, lock=lock)
    return


def resetSelectSkinClusterBindPose():
    sel = mc.ls(sl=True)
    if not sel:
        return
    
    for sl in sel:
        dc.resetSkinPose(sl)
    
    return


def exportSelectSkinClusterWeight():
    sel = mc.ls(sl=True)
    if not sel:
        return
    
    basicFilter = "*.json"
    result = mc.fileDialog2(fileFilter=basicFilter, fm=0)
    path, fileName = os.path.split(result[0])
    # pm.displayInfo((path,fileName))
    dc.exportSkinClusterWeight(sel[0], path, fileName)
    return


def importSelectSkinClusterWeight():
    sel = mc.ls(sl=True)
    if not sel:
        return
    basicFilter = "*.json"
    result = mc.fileDialog2(fileFilter=basicFilter, fm=1)
    path, fileName = os.path.split(result[0])
    dc.importSkinWeight(sel[0], path, fileName)
    
    return


def pruneSmallWeight(mode=0):
    if mode == 0:
        for sl in mc.ls(sl=True):
            dc.pruneSmallWeight(sl)
    
    elif mode == 1:
        for sl in mc.ls(type="skinCluster"):
            geo = mc.skinCluster(sl, q=True, g=True)[0]
            dc.pruneSmallWeight(geo)
    return


def removeUnusedSkinClusterInf(mode=0):
    if mode == 0:
        for sl in mc.ls(sl=True):
            dc.removeUnusedSkinClusterInf(sl)
    elif mode == 1:
        for sl in mc.ls(type="skinCluster"):
            geo = mc.skinCluster(sl, q=True, g=True)[0]
            dc.removeUnusedSkinClusterInf(geo)
    
    return

if __name__ == '__main__':
    pass